import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Progress, Badge, Spin, message } from 'antd';
import { Icon } from '@iconify/react';
import ReactECharts from 'echarts-for-react';
import { PageHeader } from '@/components';
import { useAuthStore } from '@/stores/useAuthStore';
import { getDashboardStats } from './api';
import type { DashboardStats, ServerStatus } from './api';
import { wsClient } from '@/utils/websocket';
import styles from './index.module.css';

const Dashboard: React.FC = () => {
  const { user } = useAuthStore();
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [serverStatus, setServerStatus] = useState<ServerStatus | null>(null);
  const [loading, setLoading] = useState(false);
  const [wsConnected, setWsConnected] = useState(false);
  
  // 实时数据历史记录（用于图表）
  const [memoryHistory, setMemoryHistory] = useState<Array<{ time: string; value: number }>>([]);
  const [cpuHistory, setCpuHistory] = useState<Array<{ time: string; value: number }>>([]);
  const maxHistoryLength = 20; // 保留最近20条数据

  // 获取统计数据
  const fetchStats = async () => {
    setLoading(true);
    try {
      const response = await getDashboardStats();
      if (response.data.success) {
        setStats(response.data.data);
      }
    } catch (error) {
      message.error('获取统计数据失败');
      console.error('Failed to fetch stats:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStats();
    
    // 创建订阅处理函数
    const handleWsOpened = () => {
      setWsConnected(true);
    };

    const handleConnected = (data: any) => {
      setWsConnected(true);
    };

    const handleServerStatus = (data: any) => {
      setServerStatus(data);
      setWsConnected(true);
      
      // 更新历史数据用于图表
      const now = new Date().toLocaleTimeString('zh-CN', { hour12: false });
      const memoryPercent = parseFloat(data.system.memoryUsagePercent);
      const heapPercent = parseFloat(data.memory.heapUsedPercent);
      
      setMemoryHistory(prev => {
        const newData = [...prev, { time: now, value: memoryPercent }];
        return newData.slice(-maxHistoryLength); // 只保留最近的数据
      });
      
      setCpuHistory(prev => {
        const newData = [...prev, { time: now, value: heapPercent }];
        return newData.slice(-maxHistoryLength);
      });
    };

    // 订阅事件
    wsClient.subscribe('ws_opened', handleWsOpened);
    wsClient.subscribe('connected', handleConnected);
    wsClient.subscribe('server_status', handleServerStatus);

    // 连接 WebSocket
    const token = localStorage.getItem('access_token');
    if (token) {
      wsClient.connect(token);
    }

    return () => {
      // 清理：取消订阅
      wsClient.unsubscribe('ws_opened', handleWsOpened);
      wsClient.unsubscribe('connected', handleConnected);
      wsClient.unsubscribe('server_status', handleServerStatus);
      // 关闭连接
      wsClient.close();
    };
  }, []);

  if (loading || !stats) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" spinning tip="加载中...">
          <div style={{ height: '200px' }} />
        </Spin>
      </div>
    );
  }

  return (
    <div className={styles.dashboard}>
      <PageHeader 
        title={`仪表板 - 欢迎回来，${user?.firstName || user?.email?.split('@')[0] || '用户'}`}
        extra={
          <Badge 
            status={wsConnected ? 'success' : 'error'} 
            text={wsConnected ? 'WebSocket 已连接' : 'WebSocket 未连接'} 
          />
        }
      />

      {/* 数据统计可视化 */}
      <Row gutter={[16, 16]} className={styles.statsRow}>
        {/* 登录统计柱状图 */}
        <Col xs={24} sm={12} lg={12}>
          <Card className={styles.card}>
            <ReactECharts
              option={{
                title: {
                  text: '登录统计(7天)',
                  left: 'center',
                  top: 10,
                  textStyle: {
                    fontSize: 14,
                    fontWeight: 'bold',
                  },
                },
                tooltip: {
                  trigger: 'axis',
                  axisPointer: {
                    type: 'shadow',
                  },
                },
                grid: {
                  left: '15%',
                  right: '10%',
                  bottom: '15%',
                  top: '30%',
                },
                xAxis: {
                  type: 'category',
                  data: ['成功', '失败', '独立用户'],
                  axisLabel: {
                    fontSize: 11,
                  },
                },
                yAxis: {
                  type: 'value',
                },
                series: [
                  {
                    name: '数量',
                    type: 'bar',
                    data: [
                      {
                        value: stats.logins.success,
                        itemStyle: { color: '#52c41a' },
                      },
                      {
                        value: stats.logins.failed,
                        itemStyle: { color: '#ff4d4f' },
                      },
                      {
                        value: stats.logins.uniqueUsers,
                        itemStyle: { color: '#1890ff' },
                      },
                    ],
                    label: {
                      show: true,
                      position: 'top',
                      fontSize: 11,
                    },
                    barWidth: '60%',
                  },
                ],
              }}
              style={{ height: '200px' }}
              notMerge={true}
              lazyUpdate={true}
            />
          </Card>
        </Col>

        {/* 文件存储仪表盘 */}
        <Col xs={24} sm={12} lg={12}>
          <Card className={styles.card}>
            <ReactECharts
              option={{
                title: {
                  text: '文件存储',
                  left: 'center',
                  top: 10,
                  textStyle: {
                    fontSize: 14,
                    fontWeight: 'bold',
                  },
                },
                series: [
                  {
                    type: 'gauge',
                    startAngle: 180,
                    endAngle: 0,
                    center: ['50%', '70%'],
                    radius: '90%',
                    min: 0,
                    max: 1000,
                    splitNumber: 5,
                    axisLine: {
                      lineStyle: {
                        width: 6,
                        color: [
                          [0.3, '#52c41a'],
                          [0.7, '#faad14'],
                          [1, '#ff4d4f'],
                        ],
                      },
                    },
                    pointer: {
                      icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
                      length: '12%',
                      width: 15,
                      offsetCenter: [0, '-55%'],
                      itemStyle: {
                        color: 'auto',
                      },
                    },
                    axisTick: {
                      length: 8,
                      lineStyle: {
                        color: 'auto',
                        width: 1,
                      },
                    },
                    splitLine: {
                      length: 10,
                      lineStyle: {
                        color: 'auto',
                        width: 2,
                      },
                    },
                    axisLabel: {
                      color: '#464646',
                      fontSize: 10,
                      distance: -35,
                      rotate: 'tangential',
                      formatter: function (value: number) {
                        if (value === 1000) {
                          return '1GB';
                        } else if (value === 750) {
                          return '750';
                        } else if (value === 500) {
                          return '500';
                        } else if (value === 250) {
                          return '250';
                        }
                        return '';
                      },
                    },
                    title: {
                      offsetCenter: [0, '-10%'],
                      fontSize: 10,
                      color: '#999',
                    },
                    detail: {
                      fontSize: 16,
                      offsetCenter: [0, '5%'],
                      valueAnimation: true,
                      formatter: function (value: number) {
                        return value + ' MB';
                      },
                      color: 'inherit',
                    },
                    data: [
                      {
                        value: parseFloat(stats.files.totalSizeMB),
                        name: `${stats.files.total} 个文件`,
                      },
                    ],
                  },
                ],
              }}
              style={{ height: '200px' }}
              notMerge={true}
              lazyUpdate={true}
            />
          </Card>
        </Col>
      </Row>

      {/* 实时监控图表 */}
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card
            title={
              <div className={styles.cardTitle}>
                <Icon icon="solar:chart-2-bold" />
                <span>系统内存使用率趋势</span>
                {wsConnected && <Badge status="processing" text="实时" />}
              </div>
            }
            className={styles.card}
          >
            <ReactECharts
              option={{
                tooltip: {
                  trigger: 'axis',
                  axisPointer: {
                    type: 'cross',
                    label: {
                      backgroundColor: '#6a7985',
                    },
                  },
                },
                grid: {
                  left: '3%',
                  right: '4%',
                  bottom: '3%',
                  containLabel: true,
                },
                xAxis: {
                  type: 'category',
                  boundaryGap: false,
                  data: memoryHistory.map(item => item.time),
                },
                yAxis: {
                  type: 'value',
                  name: '使用率 (%)',
                  min: 0,
                  max: 100,
                  axisLabel: {
                    formatter: '{value}%',
                  },
                },
                series: [
                  {
                    name: '内存使用率',
                    type: 'line',
                    smooth: true,
                    areaStyle: {
                      color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                          {
                            offset: 0,
                            color: 'rgba(24, 144, 255, 0.5)',
                          },
                          {
                            offset: 1,
                            color: 'rgba(24, 144, 255, 0.05)',
                          },
                        ],
                      },
                    },
                    lineStyle: {
                      width: 2,
                      color: '#1890ff',
                    },
                    itemStyle: {
                      color: '#1890ff',
                    },
                    data: memoryHistory.map(item => item.value),
                  },
                ],
              }}
              style={{ height: '300px' }}
              notMerge={true}
              lazyUpdate={true}
            />
          </Card>
        </Col>

        <Col xs={24} lg={12}>
          <Card
            title={
              <div className={styles.cardTitle}>
                <Icon icon="solar:database-bold" />
                <span>进程堆内存使用率趋势</span>
                {wsConnected && <Badge status="processing" text="实时" />}
              </div>
            }
            className={styles.card}
          >
            <ReactECharts
              option={{
                tooltip: {
                  trigger: 'axis',
                  axisPointer: {
                    type: 'cross',
                    label: {
                      backgroundColor: '#6a7985',
                    },
                  },
                },
                grid: {
                  left: '3%',
                  right: '4%',
                  bottom: '3%',
                  containLabel: true,
                },
                xAxis: {
                  type: 'category',
                  boundaryGap: false,
                  data: cpuHistory.map(item => item.time),
                },
                yAxis: {
                  type: 'value',
                  name: '使用率 (%)',
                  min: 0,
                  max: 100,
                  axisLabel: {
                    formatter: '{value}%',
                  },
                },
                series: [
                  {
                    name: '堆内存使用率',
                    type: 'line',
                    smooth: true,
                    areaStyle: {
                      color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                          {
                            offset: 0,
                            color: 'rgba(82, 196, 26, 0.5)',
                          },
                          {
                            offset: 1,
                            color: 'rgba(82, 196, 26, 0.05)',
                          },
                        ],
                      },
                    },
                    lineStyle: {
                      width: 2,
                      color: '#52c41a',
                    },
                    itemStyle: {
                      color: '#52c41a',
                    },
                    data: cpuHistory.map(item => item.value),
                  },
                ],
              }}
              style={{ height: '300px' }}
              notMerge={true}
              lazyUpdate={true}
            />
          </Card>
        </Col>
      </Row>

      {/* 服务器信息和实时状态 */}
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card 
            title={
              <div className={styles.cardTitle}>
                <Icon icon="solar:server-bold" />
                <span>服务器信息</span>
              </div>
            }
            className={styles.card}
          >
            <ReactECharts
              option={{
                tooltip: {
                  trigger: 'item',
                  formatter: '{b}: {c}',
                },
                grid: {
                  left: '3%',
                  right: '4%',
                  bottom: '3%',
                  containLabel: true,
                },
                xAxis: {
                  type: 'value',
                  boundaryGap: [0, 0.01],
                },
                yAxis: {
                  type: 'category',
                  data: ['CPU核心', '运行时间', '内存', '平台', 'Node版本', '主机'],
                },
                series: [
                  {
                    name: '服务器信息',
                    type: 'bar',
                    data: [
                      { 
                        value: stats.server.cpus,
                        itemStyle: { color: '#1890ff' },
                      },
                      { 
                        value: parseInt(stats.server.uptime.split(' ')[0]) || 1,
                        itemStyle: { color: '#52c41a' },
                      },
                      { 
                        value: parseFloat(stats.server.totalMemory.split(' ')[0]),
                        itemStyle: { color: '#faad14' },
                      },
                      {
                        value: 1,
                        itemStyle: { color: '#722ed1' },
                      },
                      {
                        value: parseInt(stats.server.nodeVersion.replace(/[^0-9]/g, '').substring(0, 2)),
                        itemStyle: { color: '#13c2c2' },
                      },
                      {
                        value: 1,
                        itemStyle: { color: '#eb2f96' },
                      },
                    ],
                    label: {
                      show: true,
                      position: 'right',
                      formatter: function(params: any) {
                        const labels = [
                          `${stats.server.cpus} 核`,
                          stats.server.uptime,
                          stats.server.totalMemory,
                          `${stats.server.platform} (${stats.server.arch})`,
                          stats.server.nodeVersion,
                          stats.server.hostname,
                        ];
                        return labels[params.dataIndex];
                      },
                      fontSize: 11,
                    },
                  },
                ],
              }}
              style={{ height: '260px' }}
              notMerge={true}
              lazyUpdate={true}
            />
          </Card>
        </Col>

        <Col xs={24} lg={12}>
      <Card 
        title={
          <div className={styles.cardTitle}>
                <Icon icon="solar:chart-bold" />
                <span>实时服务器状态</span>
                {wsConnected && <Badge status="processing" text="实时更新中" />}
          </div>
        }
            className={styles.card}
          >
            {serverStatus ? (
              <div className={styles.serverStatus}>
                <div className={styles.statusItem}>
                  <div className={styles.statusLabel}>
                    <Icon icon="solar:chart-2-bold" style={{ marginRight: '8px' }} />
                    系统内存使用率
                  </div>
                  <Progress 
                    percent={parseFloat(serverStatus.system.memoryUsagePercent)} 
                    status={parseFloat(serverStatus.system.memoryUsagePercent) > 80 ? 'exception' : 'active'}
                    strokeColor={{
                      '0%': '#108ee9',
                      '100%': '#87d068',
                    }}
                  />
                  <div className={styles.statusDetail}>
                    已用: {serverStatus.system.usedMemory} GB / 总计: {serverStatus.system.totalMemory} GB
                  </div>
                </div>

                <div className={styles.statusItem}>
                  <div className={styles.statusLabel}>
                    <Icon icon="solar:database-bold" style={{ marginRight: '8px' }} />
                    进程堆内存使用率
                  </div>
                  <Progress 
                    percent={parseFloat(serverStatus.memory.heapUsedPercent)} 
                    status={parseFloat(serverStatus.memory.heapUsedPercent) > 80 ? 'exception' : 'active'}
                    strokeColor={{
                      '0%': '#108ee9',
                      '100%': '#87d068',
                    }}
                  />
                  <div className={styles.statusDetail}>
                    已用: {serverStatus.memory.heapUsed} MB / 总计: {serverStatus.memory.heapTotal} MB
                  </div>
                </div>

                <div className={styles.statusItem}>
                  <div className={styles.statusLabel}>
                    <Icon icon="solar:cpu-bolt-bold" style={{ marginRight: '8px' }} />
                    系统负载
                  </div>
                  <ReactECharts
                    option={{
                      series: [
                        {
                          type: 'gauge',
                          center: ['50%', '60%'],
                          startAngle: 200,
                          endAngle: -20,
                          min: 0,
                          max: serverStatus.system.cpuCount,
                          splitNumber: 8,
                          itemStyle: {
                            color: '#1890ff',
                          },
                          progress: {
                            show: true,
                            width: 18,
                          },
                          pointer: {
                            show: false,
                          },
                          axisLine: {
                            lineStyle: {
                              width: 18,
                            },
                          },
                          axisTick: {
                            distance: -25,
                            splitNumber: 5,
                            lineStyle: {
                              width: 1,
                              color: '#999',
                            },
                          },
                          splitLine: {
                            distance: -30,
                            length: 12,
                            lineStyle: {
                              width: 2,
                              color: '#999',
                            },
                          },
                          axisLabel: {
                            distance: -15,
                            color: '#999',
                            fontSize: 12,
                          },
                          anchor: {
                            show: false,
                          },
                          title: {
                            show: false,
                          },
                          detail: {
                            valueAnimation: true,
                            width: '60%',
                            lineHeight: 40,
                            borderRadius: 8,
                            offsetCenter: [0, '-15%'],
                            fontSize: 24,
                            fontWeight: 'bolder',
                            formatter: '{value}',
                            color: 'inherit',
                          },
                          data: [
                            {
                              value: serverStatus.system.loadavg[0].toFixed(2),
                              name: '1分钟负载',
                            },
                          ],
                        },
                      ],
                    }}
                    style={{ height: '200px' }}
                    notMerge={true}
                    lazyUpdate={true}
                  />
                  <div style={{ textAlign: 'center', marginTop: '-20px', color: '#999' }}>
                    <div style={{ fontSize: '12px' }}>
                      5分钟: {serverStatus.system.loadavg[1].toFixed(2)} | 15分钟: {serverStatus.system.loadavg[2].toFixed(2)}
                    </div>
                    <div style={{ fontSize: '11px', marginTop: '4px' }}>
                      CPU核心数: {serverStatus.system.cpuCount}
                    </div>
                  </div>
                </div>

                <div className={styles.statusItem} style={{ marginBottom: 0 }}>
                  <div className={styles.statusLabel}>
                    <Icon icon="solar:server-square-update-bold" style={{ marginRight: '8px' }} />
                    资源占用详情
                  </div>
                  <ReactECharts
                    option={{
                      radar: {
                        indicator: [
                          { name: '已用内存', max: parseFloat(serverStatus.system.totalMemory) },
                          { name: '空闲内存', max: parseFloat(serverStatus.system.totalMemory) },
                          { name: '进程内存', max: 1000 },
                          { name: '堆内存', max: parseFloat(serverStatus.memory.heapTotal) },
                          { name: 'CPU核心', max: 40 },
                        ],
                        shape: 'polygon',
                        splitNumber: 4,
                        axisName: {
                          color: '#999',
                          fontSize: 11,
                        },
                        splitArea: {
                          areaStyle: {
                            color: ['rgba(24, 144, 255, 0.05)', 'rgba(24, 144, 255, 0.1)'],
                          },
                        },
                      },
                      series: [
                        {
                          type: 'radar',
                          data: [
                            {
                              value: [
                                parseFloat(serverStatus.system.usedMemory),
                                parseFloat(serverStatus.system.freeMemory),
                                parseFloat(serverStatus.memory.rss),
                                parseFloat(serverStatus.memory.heapUsed),
                                serverStatus.system.cpuCount,
                              ],
                              name: '资源占用',
                              areaStyle: {
                                color: 'rgba(24, 144, 255, 0.3)',
                              },
                              lineStyle: {
                                color: '#1890ff',
                                width: 2,
                              },
                              itemStyle: {
                                color: '#1890ff',
                              },
                            },
                          ],
                        },
                      ],
                    }}
                    style={{ height: '220px' }}
                    notMerge={true}
                    lazyUpdate={true}
                  />
                </div>
              </div>
            ) : (
              <div style={{ textAlign: 'center', padding: '40px 0' }}>
                <Spin spinning tip={wsConnected ? '等待服务器数据推送...' : '连接WebSocket中...'}>
                  <div style={{ height: '100px' }} />
                </Spin>
              </div>
            )}
      </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard;

